package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    @Override
    public void saveItemById(Long id) {
        try {
            // 查询一个酒店数据
            Item item = itemClient.queryItemById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            String json = JSON.toJSONString(itemDoc);
            // 创建请求
            IndexRequest request = new IndexRequest("item").id(id.toString());
            // 设置参数
            request.source(json, XContentType.JSON);
            // 执行请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteItemById(Long id) {
        try {
            // 创建请求
            DeleteRequest request = new DeleteRequest("item",id.toString()) ;
            // 执行请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> ListSuggestion(String prefix) {
        try {
            // 创建请求
            SearchRequest request = new SearchRequest("item");
            // 设置参数
            request.source().suggest(
                    new SuggestBuilder().addSuggestion("suggest1", // 查询名称(自定义)
                            SuggestBuilders.completionSuggestion("suggestion") // 自动补全字段名
                                    .prefix(prefix) // 查询以 北京 开头的词条
                                    .skipDuplicates(true) // 重复词条跳过
                                    .size(10) // 最多取前10条
                    )
            );
            // 执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 解析结果
            List<String> list = new ArrayList<>();
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggest1 = suggest.getSuggestion("suggest1");
            List<CompletionSuggestion.Entry.Option> options = suggest1.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                String term = option.getText().string();
                list.add(term);
            }
            // 返回结果
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams parms) {
        try {
            // 创建请求
            SearchRequest request = new SearchRequest("item");
            // 创建基本请求
            this.buildBasicQuery(parms, request);
            // 设置参数
            request.source().size(0); // 结果中不包含文档详情
            request.source().aggregation(
                    AggregationBuilders.terms("brandAgg").field("brand").size(50)
            );
            request.source().aggregation(
                    AggregationBuilders.terms("categoryAgg").field("category").size(50)
            );
            // 执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            // 解析
            // 获取品牌
            List<String> brandList = fetchAgg(response, "brandAgg");
            List<String> categoryList = fetchAgg(response, "categoryAgg");

            // 响应结果
            HashMap<String, List<String>> map = new HashMap<>();
            map.put("brand", brandList);
            map.put("category", categoryList);
            return map;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> fetchAgg(SearchResponse response, String aggName) {
        // 1. 创建list存结果
        List<String> brandList = new ArrayList<>();
        // 2. 拿aggregations
        Aggregations aggregations = response.getAggregations();
        // 3. 拿对应名字的结果
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        // 4. 遍历拿桶key
        for (Terms.Bucket bucket : buckets) {
            String brand = bucket.getKeyAsString();
            brandList.add(brand);
        }
        // 5. 返回keys
        return brandList;
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.关键字搜索
        String key = params.getKey();
        // 若key为空，无条件查询
        if (StringUtils.isBlank(params.getKey())) {
            boolQuery.must(
                    QueryBuilders.matchAllQuery()
            );
        } else {
            boolQuery.must(
                    QueryBuilders.matchQuery("all", key)
            );
        }
        // 3.分类条件
        if ( !StringUtils.isBlank(params.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        // 4.品牌条件
        if ( !StringUtils.isBlank(params.getBrand()) ) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 5.价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrice()*100)
                    .lte(params.getMaxPrice()*100)
            );
        }

        // 6. 复合查询-算分函数查询
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        ).boostMode(CombineFunction.SUM);

        // 6.放入source
        request.source().query(functionScoreQuery);
    }

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        try {
            // 创建请求
            SearchRequest request = new SearchRequest("item");
            // 创建基本请求
            buildBasicQuery(params, request);
            // 排序
            if (!StringUtils.isBlank(params.getSortBy())) {
                if ("sold".equals(params.getSortBy())) {
                    // 按销量排 降序
                    request.source().sort(params.getSortBy(), SortOrder.DESC);
                }
                if ("price".equals(params.getSortBy())) {
                    // 按价格排 升序
                    request.source().sort(params.getSortBy(), SortOrder.ASC);
                }
            }

            // 分页
            request.source().from((params.getPage() - 1) * params.getSize()).size(params.getSize());

            // 高亮
            request.source().highlighter(
                    new HighlightBuilder().field("name").requireFieldMatch(false)
            );

            // 执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            // 解析结果
            PageDTO<ItemDoc> pageDTO = processResponse(response);
            return pageDTO;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageDTO<ItemDoc> processResponse(SearchResponse response) {
        // 解析响应
        SearchHits searchHits = response.getHits();
        // 1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 2. 获取文档数组
        SearchHit[] hits = searchHits.getHits();
        // 3.遍历
        ArrayList<ItemDoc> items = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            // 高亮字段处理
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮的name
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖原name
                    itemDoc.setName(name);
                }
            }
            items.add(itemDoc);

        }
        // 封装返回
        return new PageDTO<ItemDoc>(total, items);
    }
}
